import 'dart:async';
import 'dart:math';

import 'package:animated_widgets/widgets/scale_animated.dart';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_vibrate/flutter_vibrate.dart';
import 'package:flutterzhuyili/utils/shared_preferences_keys.dart';
import 'package:tcard/tcard.dart';

import '../../main.dart';

///@author xuziqiang
/// @date 2020/8/19 10:00

class CardPage extends StatefulWidget {
  int level = 1;

  CardPage(this.level);

  @override
  State<StatefulWidget> createState() {
    return _CardPageState(this.level);
  }
}

class _CardPageState extends State<CardPage> {
  int level = 1;
  int _time = 0;
  int score = 0;
  int errorTimes = 0;

  //球的數量 ,刷新頻率 ，出錯次數的限制 ，時間的限制
  // Normal 4  easy 5 medium 6 hard 7 crazy 8
  //刷新频率  Normal 5次一刷    easy 4次一刷   medium 4次一刷 hard  4次一刷 crazy  4次一刷
  //出错次数限制               5  4 4   3 2
  //时间限制   有分数限制
  int allCardNum = 4;
  int refreshRate = 5;
  int maxErrorTimes = 5;
  int timeLimit = 15;
  int goal = 15;

  int nowTrueIndex = 0;

  bool animationOver = true;

  List<int> imagePathList = List();
  List<int> leftPathList = List();
  List<int> rightPathList = List();

  DIFFICULTY _difficulty = DIFFICULTY.Normal;

  Timer _timer;

  TCardController _controller = TCardController();
  List<Widget> _cards;

  _CardPageState(this.level);

  void init() {
    _time = 0;
    _initTime();
    _initDifficulty(level);
    errorTimes = 0;
    score = 0;
    imagePathList.clear();
    leftPathList.clear();
    rightPathList.clear();

    int leftCount = 1;
    int rightCount = 1;

    for (int i = 0; i < allCardNum - 2; i++) {
      if (Random().nextBool()) {
        leftCount++;
      } else {
        rightCount++;
      }
    }

    for (int i = 0; i < leftCount; i++) {
      getRandomNum(leftPathList, 10, rightPathList);
    }
    for (int i = 0; i < rightCount; i++) {
      getRandomNum(rightPathList, 10, leftPathList);
    }

    var leftAndRight = leftPathList + rightPathList;

    for (int i = 0; i < 100; i++) {
      imagePathList.add(leftAndRight[Random().nextInt(leftAndRight.length)]);
    }
    _cards = imagePathList
        .map((e) => Container(
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(12.0)),
                child: Container(
                  color: Colors.white,
                  height: 80,
                  child: Center(
                    child: SizedBox(
                      height: 165,
                      width: 165,
                      child: new Image.asset(
                        "assets/images/files/ball/rollball_sprite_$e.png",
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                ),
              ),
            ))
        .toList();
  }

  void remix() {
    //效率有點堪憂 但是影響不大
    var tempList = leftPathList + rightPathList;
    leftPathList.clear();
    rightPathList.clear();
    tempList.forEach((element) {
      if (Random().nextBool()) {
        leftPathList.add(element);
      } else {
        rightPathList.add(element);
      }
    });
    if (leftPathList.isEmpty || rightPathList.isEmpty) {
      remix();
    }
  }

  void reSetLeftAndRight() {}

  void getRandomNum(List<int> list, int max, List<int> list2) {
    int f = Random().nextInt(max) + 1;
    if (list.contains(f) || list2.contains(f)) {
      getRandomNum(list, max, list2);
    } else {
      list.add(f);
    }
  }

  @override
  void initState() {
    super.initState();
    if (sp.hasKey(SharedPreferencesKeys.cardLevel)) {
      level = sp.getInt(SharedPreferencesKeys.cardLevel);
    }
    init();
  }

  void _initTime() {
    if (_timer != null) _timer.cancel();

    const tenMs = const Duration(seconds: 1);
    var callback = (timer) => {
          setState(() {
            _time = _time + 1;
            if (_time > timeLimit) {
              _showErrorDialog('当前已经超出时间限制。');
              _timer.cancel();
            }
          })
        };
    _timer = Timer.periodic(tenMs, callback);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      body: Column(
        children: <Widget>[
          SizedBox(
            height: 30,
          ),
          Container(
            height: 50,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                IconButton(
                  icon: Icon(
                    Icons.refresh,
                    size: 30,
                  ),
                  onPressed: () {
                    setState(() {
                      init();
                    });
                    var duration = new Duration(milliseconds: 50);
                    new Future.delayed(duration, () {
                      _controller.reset();
                    });
                  },
                ),
                Text(
                  'Lv.$level',
                  style: TextStyle(fontSize: 24),
                ),
                AnimatedSwitcher(
                  duration: const Duration(milliseconds: 500),
                  transitionBuilder:
                      (Widget child, Animation<double> animation) {
                    //执行缩放动画
                    return ScaleTransition(child: child, scale: animation);
                  },
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      _animationText('$_time', 200),
                      Text(' S', style: TextStyle(fontSize: 18)),
                    ],
                  ),
                )
              ],
            ),
          ),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text('得分 ', style: TextStyle(fontSize: 18)),
                    _animationText('$score', 200),
                  ],
                ),
                Text('目标 $goal', style: TextStyle(fontSize: 18)),
                Text('出错次数 $errorTimes/$maxErrorTimes',
                    style: TextStyle(fontSize: 18)),
              ],
            ),
          ),
          Text('注意观察，左右分类', style: TextStyle(fontSize: 24)),
          Expanded(
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 3,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      _sideWidget(leftPathList),
                      FlatButton(
                        onPressed: () {
                          if (animationOver) {
                            _goLeft(_controller.index);
                          }
                        },
                        color: Colors.transparent,
                        child: Container(
                          height: 80,
                          child: Center(
                            child: Text(
                              '向左<',
                              style: TextStyle(fontSize: 25),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 6,
                  child: _centerWidget(),
                ),
                Expanded(
                  flex: 3,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      _sideWidget(rightPathList),
                      FlatButton(
                        color: Colors.transparent,
                        child: Container(
                          height: 80,
                          child: Center(
                            child: Text(
                              '向右>',
                              style: TextStyle(fontSize: 25),
                            ),
                          ),
                        ),
                        onPressed: () {
                          if (animationOver) {
                            _goRight(_controller.index);
                          }
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _sideWidget(List<int> _list) {
    return Container(
      height: 400,
      child: ListView.builder(
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _list.length,
        itemBuilder: (BuildContext context, int index) {
          return AnimationConfiguration.staggeredList(
            position: index,
            duration: const Duration(milliseconds: 375),
            child: SlideAnimation(
              verticalOffset: 50.0,
              child: FadeInAnimation(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ScaleAnimatedWidget.tween(
                    enabled: _list[index] == nowTrueIndex,
                    duration: Duration(milliseconds: 200),
                    scaleDisabled: 1,
                    scaleEnabled: 1.2,
                    animationFinished: (value) {
                      if (value) {
                        nowTrueIndex = 0;
                      }
                    },
                    child: Container(
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        child: Container(
                          color: Color(0x222196F3),
                          height: 80,
                          child: Center(
                            child: Container(
                              child: SizedBox(
                                height: 65,
                                width: 65,
                                child: new Image.asset(
                                  "assets/images/files/ball/rollball_sprite_${_list[index]}.png",
                                  fit: BoxFit.contain,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  _centerWidget() {
    return new Container(
      height: 310,
      child: TCard(
        onForward: (int index, SwipInfo info) {
          animationOver = true;
        },
        cards: _cards,
        size: Size(300, 300),
        controller: _controller,
        onBack: (index) {},
        onEnd: () {},
      ),
    );
  }

  _goLeft(int index) {
    animationOver = false;
    if (leftPathList.contains(imagePathList[index])) {
      //成功了
      setState(() {
        score++;
        nowTrueIndex = imagePathList[index];
      });
      Vibrate.feedback(FeedbackType.success);
      _controller.forward(direction: SwipDirection.Left);
      if (score >= goal) {
        _showNextLevelDialog();
        return;
      }
      if (score % 5 == 0) {
        remix();
      }
    } else {
      setState(() {
        errorTimes++;
        if (errorTimes > maxErrorTimes) {
          _timer.cancel();
          _showErrorDialog('当前错误次数已经到到上限。');
        }
      });
      animationOver = true;
      Vibrate.feedback(FeedbackType.warning);
    }
  }

  _goRight(int index) {
    animationOver = false;
    if (rightPathList.contains(imagePathList[index])) {
      //成功了
      setState(() {
        score++;
        nowTrueIndex = imagePathList[index];
      });

      Vibrate.feedback(FeedbackType.success);
      _controller.forward(direction: SwipDirection.Right);
      if (score >= goal) {
        _showNextLevelDialog();
        return;
      }
      if (score % 5 == 0) {
        remix();
      }
    } else {
      setState(() {
        errorTimes++;
        if (errorTimes > maxErrorTimes) {
          _timer.cancel();
          _showErrorDialog('当前错误次数已经到到上限。');
        }
      });
      animationOver = true;
      Vibrate.feedback(FeedbackType.warning);
    }
  }

  _addMoreCard(int cards) {
    setState(() {
      for (int i = 0; i < cards; i++) {
        if (Random().nextBool()) {
          getRandomNum(leftPathList, 10, rightPathList);
        } else {
          getRandomNum(rightPathList, 10, leftPathList);
        }
      }
      var leftAndRight = leftPathList + rightPathList;

      for (int i = 0; i < 100; i++) {
        imagePathList.add(leftAndRight[Random().nextInt(leftAndRight.length)]);
      }
      _cards = imagePathList
          .map((e) => Container(
                child: ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                  child: Container(
                    color: Colors.white,
                    height: 80,
                    child: Center(
                      child: SizedBox(
                        height: 165,
                        width: 165,
                        child: new Image.asset(
                          "assets/images/files/ball/rollball_sprite_$e.png",
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ),
                ),
              ))
          .toList();
    });
    var duration = new Duration(milliseconds: 30);
    new Future.delayed(duration, () {
      _controller.reset();
    });
  }

  _showNextLevelDialog() {
    _timer.cancel();
    AwesomeDialog(
      dismissOnTouchOutside: false,
      context: context,
      animType: AnimType.TOPSLIDE,
      dialogType: DialogType.SUCCES,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('恭喜成功过关:'),
          Text('是否继续前往下一关'),
        ],
      ),
      btnCancelText: '返回',
      btnCancelOnPress: () {
        Navigator.pop(context);
      },
      btnOkText: '继续',
      btnOkOnPress: () async {
        level++;
        sp.putInt(SharedPreferencesKeys.cardLevel, level);
        setState(() {
          init();
        });
        var duration = new Duration(milliseconds: 50);
        new Future.delayed(duration, () {
          _controller.reset();
        });
      },
    )..show();
  }

  _showErrorDialog(String str) {
    AwesomeDialog(
      dismissOnTouchOutside: false,
      context: context,
      animType: AnimType.TOPSLIDE,
      dialogType: DialogType.ERROR,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('$str'),
          Text('是否重新挑战？'),
        ],
      ),
      btnCancelText: '返回',
      btnCancelOnPress: () {
        Navigator.pop(context);
      },
      btnOkText: '是',
      btnOkOnPress: () async {
        setState(() {
          _timer.cancel();
          init();
        });
        var duration = new Duration(milliseconds: 50);
        new Future.delayed(duration, () {
          _controller.reset();
        });
      },
    )..show();
  }

  _initDifficulty(int level) {
    //初始化难度
    if (level > 0 && level <= 5) {
      _difficulty = DIFFICULTY.Normal;
    } else if (level > 5 && level <= 10) {
      _difficulty = DIFFICULTY.Easy;
    } else if (level > 10 && level <= 20) {
      _difficulty = DIFFICULTY.Medium;
    } else if (level > 20 && level <= 30) {
      _difficulty = DIFFICULTY.Hard;
    } else if (level > 30) {
      _difficulty = DIFFICULTY.Crazy;
    }
    //球的數量 ,刷新頻率 ，出錯次數的限制 ，時間的限制
    // Normal 4  easy 5 medium 6 hard 7 crazy 8
    //刷新频率  Normal 5次一刷    easy 4次一刷   medium 4次一刷 hard  4次一刷 crazy  4次一刷
    //出错次数限制               5  4 4   3 2
    //时间限制   有分数限制
    switch (_difficulty) {
      case DIFFICULTY.Normal:
        allCardNum = 4;
        refreshRate = 5;
        maxErrorTimes = 5;
        timeLimit = 15;
        goal = 15;
        break;
      case DIFFICULTY.Easy:
        allCardNum = 5;
        refreshRate = 4;
        maxErrorTimes = 4;
        timeLimit = 15;
        goal = 20;
        break;
      case DIFFICULTY.Medium:
        allCardNum = 6;
        refreshRate = 4;
        maxErrorTimes = 4;
        timeLimit = 15;
        goal = 25;
        break;
      case DIFFICULTY.Hard:
        allCardNum = 7;
        refreshRate = 4;
        maxErrorTimes = 3;
        timeLimit = 15;
        goal = 30;
        break;
      case DIFFICULTY.Crazy:
        allCardNum = 8;
        refreshRate = 4;
        maxErrorTimes = 2;
        timeLimit = 15;
        goal = 35;
        break;
    }
  }

  _animationText(String str, int duration) {
    return AnimatedSwitcher(
        duration: Duration(milliseconds: duration),
        transitionBuilder: (Widget child, Animation<double> animation) {
          //执行缩放动画
          return ScaleTransition(child: child, scale: animation);
        },
        child: Text(
          '$str',
          style: TextStyle(fontSize: 20),
          key: ValueKey<String>(str),
        ));
  }
//  Widget center() {
//    return;
//  }
}

enum DIFFICULTY { Normal, Easy, Medium, Hard, Crazy }
